#!/bin/bash
# 民法典H5应用 - 直接部署脚本
# 服务器IP: 124.220.227.52
# 项目路径: /home/ubuntu/civil
# 使用方法: ./deploy.sh [init|update|restart|stop|status|logs]

set -e

# 配置变量
PROJECT_ROOT="/home/ubuntu/civil"
BACKEND_DIR="$PROJECT_ROOT/backend"
FRONTEND_DIR="$PROJECT_ROOT/frontend"
LOG_DIR="$PROJECT_ROOT/logs"
VENV_DIR="$BACKEND_DIR/venv"

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 未安装，请先运行 setup-server.sh"
        exit 1
    fi
}

# 初始化部署
init_deploy() {
    echo -e "${GREEN}======================================"
    echo "  民法典H5应用 - 初始化部署"
    echo "  服务器: 124.220.227.52"
    echo "======================================${NC}"
    
    # 1. 检查必要的命令
    log_info "[1/8] 检查系统环境..."
    check_command python3
    check_command node
    check_command npm
    check_command nginx
    check_command supervisorctl
    log_success "系统环境检查通过"
    
    # 2. 创建必要的目录
    log_info "[2/8] 创建项目目录..."
    mkdir -p $LOG_DIR
    log_success "目录创建完成"
    
    # 3. 部署后端
    log_info "[3/8] 部署后端..."
    deploy_backend
    
    # 4. 部署前端
    log_info "[4/8] 部署前端..."
    deploy_frontend
    
    # 5. 配置MongoDB
    log_info "[5/8] 配置MongoDB..."
    configure_mongodb
    
    # 6. 配置Nginx
    log_info "[6/8] 配置Nginx..."
    configure_nginx
    
    # 7. 配置Supervisor
    log_info "[7/8] 配置Supervisor..."
    configure_supervisor
    
    # 8. 启动服务
    log_info "[8/8] 启动所有服务..."
    start_services
    
    echo ""
    log_success "✅ 部署完成！"
    echo ""
    echo -e "${YELLOW}访问地址: http://124.220.227.52${NC}"
    echo ""
    show_status
}

# 部署后端
deploy_backend() {
    cd $BACKEND_DIR
    
    # 创建虚拟环境
    if [ ! -d "$VENV_DIR" ]; then
        log_info "创建Python虚拟环境..."
        python3 -m venv venv
    fi
    
    # 激活虚拟环境并安装依赖
    log_info "安装Python依赖..."
    source venv/bin/activate
    pip install --upgrade pip
    pip install -r requirements.txt
    deactivate
    
    # 检查环境变量文件
    if [ ! -f "$BACKEND_DIR/.env" ]; then
        if [ -f "$PROJECT_ROOT/env.example" ]; then
            log_warning "未找到.env文件，从env.example复制..."
            cp $PROJECT_ROOT/env.example $BACKEND_DIR/.env
            log_warning "⚠️  请编辑 $BACKEND_DIR/.env 配置正确的环境变量"
            log_warning "⚠️  特别是MongoDB连接信息和JWT密钥"
        fi
    fi
    
    log_success "后端部署完成"
}

# 部署前端
deploy_frontend() {
    cd $FRONTEND_DIR
    
    # 安装依赖
    log_info "安装Node.js依赖..."
    npm install
    
    # 构建生产版本
    log_info "构建前端生产版本..."
    npm run build
    
    log_success "前端构建完成，输出目录: $FRONTEND_DIR/dist"
}

# 配置MongoDB
configure_mongodb() {
    # 检查MongoDB是否运行
    if ! systemctl is-active --quiet mongod; then
        log_warning "MongoDB未运行，正在启动..."
        sudo systemctl start mongod
    fi
    
    log_info "MongoDB运行中，数据库准备就绪"
    log_warning "如需创建数据库用户，请手动执行MongoDB命令"
    
    log_success "MongoDB配置完成"
}

# 配置Nginx
configure_nginx() {
    # 复制Nginx配置文件
    log_info "复制Nginx配置..."
    sudo cp $PROJECT_ROOT/deploy/nginx/civil-code.conf /etc/nginx/sites-available/civil-code.conf
    
    # 创建软链接启用站点
    if [ ! -L /etc/nginx/sites-enabled/civil-code.conf ]; then
        sudo ln -s /etc/nginx/sites-available/civil-code.conf /etc/nginx/sites-enabled/civil-code.conf
    fi
    
    # 删除默认站点（可选）
    if [ -L /etc/nginx/sites-enabled/default ]; then
        log_info "移除Nginx默认站点..."
        sudo rm /etc/nginx/sites-enabled/default
    fi
    
    # 测试Nginx配置
    log_info "测试Nginx配置..."
    sudo nginx -t
    
    log_success "Nginx配置完成"
}

# 配置Supervisor
configure_supervisor() {
    # 复制Supervisor配置
    log_info "复制Supervisor配置..."
    sudo cp $PROJECT_ROOT/deploy/supervisor/civil-code-backend.conf /etc/supervisor/conf.d/
    
    # 重新加载Supervisor配置
    log_info "重新加载Supervisor配置..."
    sudo supervisorctl reread
    sudo supervisorctl update
    
    log_success "Supervisor配置完成"
}

# 启动所有服务
start_services() {
    # 启动后端
    log_info "启动后端服务..."
    sudo supervisorctl start civil-code-backend
    
    # 重启Nginx
    log_info "重启Nginx..."
    sudo systemctl reload nginx
    
    log_success "所有服务已启动"
}

# 更新部署
update_deploy() {
    echo -e "${GREEN}======================================"
    echo "  民法典H5应用 - 更新部署"
    echo "======================================${NC}"
    
    # 停止后端服务
    log_info "[1/4] 停止后端服务..."
    sudo supervisorctl stop civil-code-backend
    
    # 更新后端
    log_info "[2/4] 更新后端..."
    cd $BACKEND_DIR
    source venv/bin/activate
    pip install -r requirements.txt --upgrade
    deactivate
    
    # 更新前端
    log_info "[3/4] 更新前端..."
    cd $FRONTEND_DIR
    npm install
    npm run build
    
    # 重启服务
    log_info "[4/4] 重启服务..."
    sudo supervisorctl start civil-code-backend
    sudo systemctl reload nginx
    
    log_success "更新完成！"
    show_status
}

# 重启服务
restart_services() {
    log_info "重启所有服务..."
    sudo supervisorctl restart civil-code-backend
    sudo systemctl reload nginx
    log_success "服务已重启"
    show_status
}

# 停止服务
stop_services() {
    log_info "停止所有服务..."
    sudo supervisorctl stop civil-code-backend
    log_success "服务已停止"
}

# 查看日志
view_logs() {
    echo -e "${BLUE}======================================"
    echo "  日志查看"
    echo "======================================${NC}"
    echo ""
    echo "选择要查看的日志："
    echo "  1) Gunicorn访问日志"
    echo "  2) Gunicorn错误日志"
    echo "  3) Supervisor标准输出"
    echo "  4) Supervisor错误输出"
    echo "  5) Nginx访问日志"
    echo "  6) Nginx错误日志"
    echo "  7) 后端应用日志"
    echo ""
    
    read -p "请选择 (1-7): " choice
    
    case $choice in
        1) tail -f $LOG_DIR/gunicorn-access.log ;;
        2) tail -f $LOG_DIR/gunicorn-error.log ;;
        3) tail -f $LOG_DIR/supervisor-stdout.log ;;
        4) tail -f $LOG_DIR/supervisor-stderr.log ;;
        5) tail -f $LOG_DIR/nginx-access.log ;;
        6) tail -f $LOG_DIR/nginx-error.log ;;
        7) tail -f $BACKEND_DIR/logs/app.log ;;
        *) log_error "无效的选择" ;;
    esac
}

# 显示状态
show_status() {
    echo ""
    echo -e "${BLUE}======================================"
    echo "  服务状态"
    echo "======================================${NC}"
    
    echo -e "\n${YELLOW}后端服务状态:${NC}"
    sudo supervisorctl status civil-code-backend || true
    
    echo -e "\n${YELLOW}Nginx状态:${NC}"
    sudo systemctl status nginx --no-pager -l | head -n 10 || true
    
    echo -e "\n${YELLOW}MongoDB状态:${NC}"
    sudo systemctl status mongod --no-pager -l | head -n 10 || true
    
    echo -e "\n${YELLOW}服务访问地址:${NC}"
    echo "  前端: http://124.220.227.52"
    echo "  API:  http://124.220.227.52/api"
    echo "  健康检查: http://124.220.227.52/api/health"
    echo ""
}

# 主函数
main() {
    case "$1" in
        init)
            init_deploy
            ;;
        update)
            update_deploy
            ;;
        restart)
            restart_services
            ;;
        stop)
            stop_services
            ;;
        status)
            show_status
            ;;
        logs)
            view_logs
            ;;
        *)
            echo "使用方法: $0 {init|update|restart|stop|status|logs}"
            echo ""
            echo "命令说明:"
            echo "  init    - 首次初始化部署"
            echo "  update  - 更新现有部署"
            echo "  restart - 重启所有服务"
            echo "  stop    - 停止所有服务"
            echo "  status  - 查看服务状态"
            echo "  logs    - 查看日志"
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
